package com.product.system.controller;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.signers.JWTSignerUtil;
import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageInfo;
import com.product.system.aop.RoleAddLogAop;
import com.product.system.domain.FactoryUser;
import com.product.system.domain.request.SysRoleSerch;
import com.product.system.domain.response.SysRole;
import com.product.system.domain.response.SysShowForm;
import com.product.system.listener.RoleDataListener;
import com.product.system.service.SysRoleService;
import com.product.system.utils.Result;
//import io.minio.MinioClient;
//import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("sysrole")
public class SysRoleController {

    @Autowired
    SysRoleService sysRoleService;

    //登录
    @Autowired
    HttpServletResponse response;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    HttpServletRequest request;



    @RequestMapping("login")
    public Result login(@RequestBody SysRole sysRole){
        //校验验证码
        String code = sysRole.getCode();//获取用户输入的验证码
        String codeRedis= (String) redisTemplate.opsForValue().get(sysRole.getUid());
        if(code==null){
            return Result.fail("请输入验证码");
        }

        if(!codeRedis.equals(code)){
            return Result.fail("验证码错误");
        }

        FactoryUser userDB= sysRoleService.selectSysRole(sysRole.getName());
        if(userDB==null){
            return Result.fail("用户名不存在");
        }

        if(!sysRole.getPassword().equals(userDB.getPassword())){
            return Result.fail("密码错误");
        }

        String md5Hex = DigestUtil.md5Hex(JSONUtil.toJsonStr(userDB) + request.getRemoteAddr());
        if(!redisTemplate.opsForValue().setIfAbsent(md5Hex,"123",5, TimeUnit.MINUTES)){
            return Result.fail("请勿重复登录");
        }


        String token = JWT.create()
                .setPayload("user", userDB)
                .setSigner(JWTSignerUtil.none())
                .sign();
        return Result.success(token);
    }


    /**
     * 验证码
     */
    @RequestMapping("createImage")
    public void createImage(String uid) throws IOException {
        //定义图形验证码的长、宽、验证码字符数、干扰元素个数
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 20);
        captcha.write(response.getOutputStream());
        redisTemplate.opsForValue().set(uid,captcha.getCode(),2, TimeUnit.MINUTES);
    }






//    @Autowired
//    private MinioClient minioClient;


//    @Value(value = "${minio.bucket}")
//    private String bucket;
//
//    @Value(value = "${minio.url}")
//    private String url;
//    @Autowired
//    private MinioClient minioClient;
//
//
//    @Value(value = "${minio.bucket}")
//    private String bucket;
//
//    @Value(value = "${minio.url}")
//    private String url;




    @GetMapping("roleList")
    public Result roleList(SysRoleSerch sysRoleSerch) {
        PageInfo<SysRole> rolePageInfo =  sysRoleService.roleList(sysRoleSerch);
        return Result.success(rolePageInfo);
    }


    @PostMapping("roleAdd")
    @RoleAddLogAop
    @Transactional
    public Result roleAdd(@RequestBody @Validated SysRole sysRole) {
        System.out.println("aaaaaaaaaaaaa");
       sysRoleService.roleAdd(sysRole);
        return Result.success("添加成功");
    }




//    @PostMapping("uploadRoleHeader")
//    public Result uploadRoleHeader(MultipartFile file) {
//
//        String fileName = UUID.randomUUID()+"_"+file.getOriginalFilename();
//
//        try {
//
//            minioClient.putObject(PutObjectArgs.builder()
//                    .object(fileName)
//                    .bucket(bucket)
//                    .stream(file.getInputStream(),file.getSize(),-1)
//                    .contentType(file.getContentType())
//                    .build());
//            return Result.success(url+fileName);
//
//        } catch (Exception aa) {
//            aa.printStackTrace();
//            return Result.fail();
//        }
//
//    }



    @GetMapping("showForm")
    public Result showForm() {

        List<SysShowForm> list = sysRoleService.showForm();


        return Result.success(list);
    }


    @PostMapping("updataRole")
    public Result updataRole(@RequestBody SysRole sysRole) {
        Boolean updataboolean = sysRoleService.roleUpdata(sysRole);
        return updataboolean?Result.success("修改成功"):Result.fail();
    }


    @GetMapping("delRole")
    public Result delRole(Integer roleId) {
       Boolean delboolean =  sysRoleService.roleDel(roleId);
        return delboolean?Result.success("删除成功"):Result.fail();
    }


    @GetMapping("excelPort")
    public void downLoad(HttpServletResponse response) throws IOException {
        List<SysRole> sysRoleList = sysRoleService.excelList();
        //指定类型
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        //指定文件名称
        String fileName = URLEncoder.encode("用户信息", "UTF-8").replaceAll("\\+", "%20");
        //指定响应头
        response.setHeader("Content-disposition","attachment;filename*=utf-8''"+fileName+".xlsx");
        EasyExcel.write(response.getOutputStream(), SysRole.class).sheet("sheet1").doWrite(sysRoleList);

    }

    @PostMapping("loadinExcel")
    public Result loadinExcel(MultipartFile file) throws IOException {
        try {
            EasyExcel.read(file.getInputStream(), SysRole.class, new RoleDataListener(sysRoleService)).doReadAll();
            return Result.success();
        } catch (Exception aa) {
            aa.printStackTrace();
            return Result.fail();
        }
    }





}
